package com.pension.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.pension.common.Util;
import com.pension.model.dao.MemberDao;
import com.pension.model.dto.Member;

@WebServlet("/account/login.action")
public class LoginServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		//1. 요청 데이터 읽기 (아이디, 비밀번호)
		String id = req.getParameter("memberId");
		String passwd = req.getParameter("passwd");
		passwd = Util.getHashedString(passwd, "SHA-1");
		
		
		//2. 데이터 처리 (db에서 조회)
		MemberDao dao = new MemberDao();
		Member member = dao.getMemberByIdAndPasswd(id, passwd);
		
		//3. 결과에 따라 이동 (성공 - home.action, 실패 - loginform.action)
		String path = null;
		if (member == null) {
			//로그인 실패
			path = "/pension/account/loginform.action";
		} else {
			//로그인 성공
			HttpSession session = req.getSession();
			session.setAttribute("loginuser", member);//로그인 처리
			
			if (req.getParameter("returnuri") != null) {
				path = req.getParameter("returnuri");
			} else {
				path = "/pension/home.action";
			}
			
		}
		resp.sendRedirect(path);
		
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		doGet(req, resp);
	}
	
}




